package com.alex.springbootdemo.security;

import com.alex.springbootdemo.model.pojo.UmsAdmin;
import com.alex.springbootdemo.service.UmsAdminService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Optional;

@Configuration
public class CurrentUserConfiguration {


    private final UmsAdminService umsAdminService;

    public CurrentUserConfiguration(UmsAdminService umsAdminService) {
        this.umsAdminService = umsAdminService;
    }

    @Bean
    public CurrentUser currentUser() {
        return new CurrentUser() {
            @Override
            public Optional<UmsAdmin> get() {
                SecurityContext context = SecurityContextHolder.getContext();
                Authentication authentication = context.getAuthentication();
                if (authentication == null) {
                    return Optional.empty();
                } else if (authentication.getPrincipal() instanceof UserDetails) {
                    UserDetails securityUser = (UserDetails) authentication.getPrincipal();
                    return Optional.of(umsAdminService.getAdminByUsername(securityUser.getUsername()));
                }else if(authentication.getPrincipal() instanceof String){
                    return Optional.of(umsAdminService.getAdminByUsername((String) authentication.getPrincipal()));
                }
                return Optional.empty();
            }
        };
    }
}
